package com.fmy.mcsecurity.login.hander;


import com.fmy.mcsecurity.commons.resp.SecurityResp;
import com.fmy.mcsecurity.commons.resp.SecurityRespEnum;
import com.fmy.mcsecurity.commons.tools.RequestTool;
import com.fmy.mcsecurity.commons.unusual.TokenVerfiyException;
import com.fmy.mcsecurity.token.model.SecurityToken;
import org.springframework.http.HttpStatus;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName LoginSuccessHandler.java
 * @Description TODO 登录业务处理接口
 * @createTime 2019年07月06日 15:23:00
 */
public interface LoginHandler<T> {

    /**
     * 登录失败、自定义返回数据内容
     */
    T resultFail(Exception e);

    /**
     * 登录成功、自动以返回信息
     */
    T resultSuccess(SecurityToken token);

    /**
     * UsernamePassParamsFilter.class 发生异常时所调用方法
     */
    default void paramsFail(HttpServletResponse response, SecurityRespEnum respEnum, Exception e) throws IOException {
        Map<String, String> result = new HashMap<>(2);
        respEnum = respEnum == null ? SecurityResp.PARAM_FAIL_ERROR : respEnum;
        result.put("code", respEnum.getCode());
        result.put("errMsg", e.getMessage());
        RequestTool.responseWriter(response, HttpStatus.OK, result);
    }

    /**
     * 返回前调用方法
     */
    void resultPrefix();

    /**
     * token 获取或验证的时候发生异常所调用的方法
     */
    default void tokenExHander(HttpServletRequest request, HttpServletResponse response, TokenVerfiyException e) throws IOException {
        Map<String, Object> result = new HashMap<>(3);
        result.put("code", e.getiEnum().getCode());
        result.put("errMsg", e.getMessage());
        RequestTool.responseWriter(response, HttpStatus.UNAUTHORIZED, result);
    }
}
